<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';

import { message, Modal, Upload } from 'ant-design-vue';

// 房间数据
const roomsData = ref([
  {
    id: 1,
    roomNumber: '101',
    area: 25.5,
    orientation: 'south',
    status: 'vacant',
    rent: 1500,
    deposit: 3000,
    facilities: '空调、热水器、WiFi、电视',
    remark: '精装修，采光好',
    images: ['https://via.placeholder.com/150x100?text=Room+101'],
    iotDevices: [
      { name: '门锁', status: 'online', type: 'lock' },
      { name: '空调', status: 'online', type: 'ac' },
      { name: '热水器', status: 'offline', type: 'heater' },
    ],
  },
  {
    id: 2,
    roomNumber: '102',
    area: 30,
    orientation: 'east',
    status: 'rented',
    rent: 1800,
    deposit: 3600,
    facilities: '空调、热水器、WiFi、洗衣机',
    remark: '带阳台，通风良好',
    images: ['https://via.placeholder.com/150x100?text=Room+102'],
    iotDevices: [
      { name: '门锁', status: 'online', type: 'lock' },
      { name: '空调', status: 'online', type: 'ac' },
      { name: '智能电表', status: 'online', type: 'meter' },
    ],
  },
  {
    id: 3,
    roomNumber: '201',
    area: 28,
    orientation: 'south',
    status: 'reserved',
    rent: 1600,
    deposit: 3200,
    facilities: '空调、热水器、WiFi',
    remark: '安静舒适',
    images: ['https://via.placeholder.com/150x100?text=Room+201'],
    iotDevices: [
      { name: '门锁', status: 'offline', type: 'lock' },
      { name: '摄像头', status: 'online', type: 'camera' },
    ],
  },
]);

// 搜索筛选状态
const searchForm = reactive({
  roomNumber: '',
  status: '',
  orientation: '',
  rentRange: [] as number[],
  selectedRowKeys: [] as number[],
});

// 表格列定义
const columns = [
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '面积(㎡)',
    dataIndex: 'area',
    key: 'area',
    width: 100,
  },
  {
    title: '朝向',
    dataIndex: 'orientation',
    key: 'orientation',
    width: 100,
    customRender: ({ text }: { text: string }) => {
      const orientationMap: Record<string, string> = {
        east: '东',
        south: '南',
        west: '西',
        north: '北',
        southeast: '东南',
        southwest: '西南',
        northeast: '东北',
        northwest: '西北',
      };
      return orientationMap[text] || text;
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '租金(元/月)',
    dataIndex: 'rent',
    key: 'rent',
    width: 120,
  },
  {
    title: '押金(元)',
    dataIndex: 'deposit',
    key: 'deposit',
    width: 120,
  },
  {
    title: 'IoT设备',
    key: 'iotDevices',
    width: 120,
    customRender: ({ record }: { record: any }) => {
      const onlineCount =
        record.iotDevices?.filter((device: any) => device.status === 'online')
          .length || 0;
      const totalCount = record.iotDevices?.length || 0;
      return `${onlineCount}/${totalCount} 在线`;
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// IoT设备表格列定义
const iotColumns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 弹窗状态
const modalVisible = ref(false);
const isEdit = ref(false);
const currentId = ref<null | number>(null);

// IoT设备管理弹窗状态
const iotModalVisible = ref(false);
const currentRoomForIOT = ref<any>(null);

// 表单数据
const formRef = ref();
const formData = reactive({
  roomNumber: '',
  area: 0,
  orientation: '',
  status: 'vacant',
  rent: 0,
  deposit: 0,
  facilities: '',
  remark: '',
  images: [] as string[],
  iotDevices: [] as any[],
});

// 表单验证规则
const rules = {
  roomNumber: [{ required: true, message: '请输入房间号' }],
  area: [{ required: true, message: '请输入面积' }],
  orientation: [{ required: true, message: '请选择朝向' }],
  status: [{ required: true, message: '请选择状态' }],
  rent: [{ required: true, message: '请输入租金' }],
  deposit: [{ required: true, message: '请输入押金' }],
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    vacant: 'green',
    reserved: 'orange',
    rented: 'blue',
    maintenance: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    vacant: '空置',
    reserved: '已预订',
    rented: '已出租',
    maintenance: '维修中',
  };
  return textMap[status] || status;
};

// 获取设备状态颜色
const getDeviceStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'red',
    fault: 'orange',
    maintenance: 'blue',
  };
  return colorMap[status] || 'default';
};

// 获取设备状态文本
const getDeviceStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    fault: '故障',
    maintenance: '维护中',
  };
  return textMap[status] || status;
};

// 获取设备类型颜色
const getDeviceTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    lock: 'blue',
    ac: 'cyan',
    heater: 'orange',
    meter: 'purple',
    camera: 'green',
    light: 'yellow',
    curtain: 'pink',
    sensor: 'gray',
  };
  return colorMap[type] || 'default';
};

// 获取设备类型文本
const getDeviceTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    lock: '门锁',
    ac: '空调',
    heater: '热水器',
    meter: '电表',
    camera: '摄像头',
    light: '照明',
    curtain: '窗帘',
    sensor: '传感器',
  };
  return textMap[type] || type;
};

// 房源统计
const roomStats = computed(() => {
  const total = roomsData.value.length;
  const vacant = roomsData.value.filter((r) => r.status === 'vacant').length;
  const rented = roomsData.value.filter((r) => r.status === 'rented').length;
  const maintenance = roomsData.value.filter(
    (r) => r.status === 'maintenance',
  ).length;

  return {
    total,
    vacant,
    rented,
    maintenance,
  };
});

// 收入统计
const incomeStats = computed(() => {
  const monthlyRent = roomStats.value.rented * 1500; // 假设平均租金1500
  const totalDeposit = roomStats.value.rented * 3000; // 假设平均押金3000
  const occupancyRate =
    roomStats.value.total > 0
      ? Math.round((roomStats.value.rented / roomStats.value.total) * 100)
      : 0;

  return {
    monthlyRent,
    totalDeposit,
    occupancyRate,
  };
});

// IoT设备统计
const iotStats = computed(() => {
  const allDevices = roomsData.value.flatMap((room) => room.iotDevices || []);
  const total = allDevices.length;
  const online = allDevices.filter((d) => d.status === 'online').length;
  const offline = allDevices.filter((d) => d.status === 'offline').length;
  const fault = allDevices.filter((d) => d.status === 'fault').length;
  const onlineRate = total > 0 ? Math.round((online / total) * 100) : 0;

  return {
    total,
    online,
    offline,
    fault,
    onlineRate,
  };
});

// 获取筛选后的数据
const filteredData = computed(() => {
  let data = roomsData.value;

  if (searchForm.roomNumber) {
    data = data.filter((item) =>
      item.roomNumber
        .toLowerCase()
        .includes(searchForm.roomNumber.toLowerCase()),
    );
  }

  if (searchForm.status) {
    data = data.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.orientation) {
    data = data.filter((item) => item.orientation === searchForm.orientation);
  }

  if (searchForm.rentRange.length === 2) {
    data = data.filter(
      (item) =>
        item.rent >= searchForm.rentRange[0] &&
        item.rent <= searchForm.rentRange[1],
    );
  }

  return data;
});

// 重置表单
const resetForm = () => {
  formData.roomNumber = '';
  formData.area = 0;
  formData.orientation = '';
  formData.status = 'vacant';
  formData.rent = 0;
  formData.deposit = 0;
  formData.facilities = '';
  formData.remark = '';
  formData.images = [];
  formData.iotDevices = [];
  formRef.value?.resetFields();
};

// 添加房源
const handleAdd = () => {
  isEdit.value = false;
  currentId.value = null;
  resetForm();
  modalVisible.value = true;
};

// 编辑房源
const handleEdit = (record: any) => {
  isEdit.value = true;
  currentId.value = record.id;
  Object.assign(formData, record);
  modalVisible.value = true;
};

// 删除房源
const handleDelete = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除房间 ${record.roomNumber} 吗？`,
    onOk: () => {
      const index = roomsData.value.findIndex((item) => item.id === record.id);
      if (index !== -1) {
        roomsData.value.splice(index, 1);
        message.success('删除成功');
      }
    },
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (searchForm.selectedRowKeys.length === 0) {
    message.warning('请选择要删除的房源');
    return;
  }

  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${searchForm.selectedRowKeys.length} 个房源吗？`,
    onOk: () => {
      const idsToDelete = new Set(searchForm.selectedRowKeys);
      roomsData.value = roomsData.value.filter(
        (item) => !idsToDelete.has(item.id),
      );
      searchForm.selectedRowKeys = [];
      message.success('批量删除成功');
    },
  });
};

// 导出数据
const handleExport = () => {
  const data = filteredData.value.map((item) => ({
    房间号: item.roomNumber,
    面积: item.area,
    朝向: getStatusText(item.orientation),
    状态: getStatusText(item.status),
    租金: item.rent,
    押金: item.deposit,
    配套设施: item.facilities,
    备注: item.remark,
  }));

  const csvContent = [
    Object.keys(data[0]).join(','),
    ...data.map((row) => Object.values(row).join(',')),
  ].join('\n');

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `房源数据_${new Date().toISOString().split('T')[0]}.csv`;
  link.click();
  message.success('导出成功');
};

// 导入数据
const handleImport = (file: any) => {
  const reader = new FileReader();
  reader.addEventListener('load', (e) => {
    try {
      const csv = e.target?.result as string;
      const lines = csv.split('\n');
      const headers = lines[0].split(',');
      const newData = lines.slice(1).map((line) => {
        const values = line.split(',');
        return {
          id: Date.now() + Math.random(),
          roomNumber: values[0],
          area: Number.parseFloat(values[1]) || 0,
          orientation: values[2],
          status: values[3],
          rent: Number.parseFloat(values[4]) || 0,
          deposit: Number.parseFloat(values[5]) || 0,
          facilities: values[6] || '',
          remark: values[7] || '',
          images: [],
          iotDevices: [],
        };
      });

      roomsData.value.push(...newData);
      message.success(`成功导入 ${newData.length} 条数据`);
    } catch {
      message.error('导入失败，请检查文件格式');
    }
  });
  reader.readAsText(file);
  return false; // 阻止自动上传
};

// 图片上传处理
const handleImageUpload = (file: any) => {
  // 模拟上传，实际项目中应该调用上传API
  const reader = new FileReader();
  reader.addEventListener('load', (e) => {
    formData.images.push(e.target?.result as string);
  });
  reader.readAsDataURL(file);
  return false;
};

// 删除图片
const handleRemoveImage = (index: number) => {
  formData.images.splice(index, 1);
};

// 保存房源
const handleSave = () => {
  formRef.value?.validate().then(() => {
    if (isEdit.value && currentId.value) {
      // 编辑模式
      const index = roomsData.value.findIndex(
        (item) => item.id === currentId.value,
      );
      if (index !== -1) {
        roomsData.value[index] = {
          ...roomsData.value[index],
          roomNumber: formData.roomNumber,
          area: formData.area,
          orientation: formData.orientation,
          status: formData.status,
          rent: formData.rent,
          deposit: formData.deposit,
          facilities: formData.facilities,
          remark: formData.remark,
          images: formData.images,
          iotDevices: formData.iotDevices,
        };
        message.success('编辑成功');
      }
    } else {
      // 添加模式
      const newRoom = {
        id: Date.now(),
        roomNumber: formData.roomNumber,
        area: formData.area,
        orientation: formData.orientation,
        status: formData.status,
        rent: formData.rent,
        deposit: formData.deposit,
        facilities: formData.facilities,
        remark: formData.remark,
        images: formData.images,
        iotDevices: formData.iotDevices,
      };
      roomsData.value.push(newRoom);
      message.success('添加成功');
    }
    modalVisible.value = false;
    resetForm();
  });
};

// 取消操作
const handleCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 打开IoT设备管理
const handleIOTManagement = (record: any) => {
  currentRoomForIOT.value = record;
  iotModalVisible.value = true;
};

// 关闭IoT设备管理
const handleIOTCancel = () => {
  iotModalVisible.value = false;
  currentRoomForIOT.value = null;
};

// 重置搜索
const resetSearch = () => {
  searchForm.roomNumber = '';
  searchForm.status = '';
  searchForm.orientation = '';
  searchForm.rentRange = [];
  searchForm.selectedRowKeys = [];
};

// 页面加载时初始化数据
onMounted(() => {
  // 这里可以调用API获取数据
  console.log('房源管理页面已加载');
});
</script>

<template>
  <div class="room-management">
    <a-card title="房源管理" :bordered="false">
      <!-- 数据统计仪表板 -->
      <div class="dashboard-section mb-4">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="总房源数"
                :value="roomStats.total"
                :value-style="{ color: '#1890ff' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="空置房源"
                :value="roomStats.vacant"
                :value-style="{ color: '#52c41a' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="已出租"
                :value="roomStats.rented"
                :value-style="{ color: '#722ed1' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="维修中"
                :value="roomStats.maintenance"
                :value-style="{ color: '#fa8c16' }"
              />
            </a-card>
          </a-col>
        </a-row>

        <a-row :gutter="16" class="mt-3">
          <a-col :span="12">
            <a-card size="small" title="收入统计">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-statistic
                    title="月租金收入"
                    :value="incomeStats.monthlyRent"
                    :precision="2"
                    suffix="元"
                    :value-style="{ color: '#52c41a' }"
                  />
                </a-col>
                <a-col :span="12">
                  <a-statistic
                    title="押金总额"
                    :value="incomeStats.totalDeposit"
                    :precision="2"
                    suffix="元"
                    :value-style="{ color: '#1890ff' }"
                  />
                </a-col>
              </a-row>
              <div class="mt-3">
                <a-progress
                  :percent="incomeStats.occupancyRate"
                  :format="(percent) => `入住率 ${percent}%`"
                  status="active"
                />
              </div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card size="small" title="IoT设备状态">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-statistic
                    title="在线设备"
                    :value="iotStats.online"
                    :value-style="{ color: '#52c41a' }"
                  />
                </a-col>
                <a-col :span="8">
                  <a-statistic
                    title="离线设备"
                    :value="iotStats.offline"
                    :value-style="{ color: '#ff4d4f' }"
                  />
                </a-col>
                <a-col :span="8">
                  <a-statistic
                    title="故障设备"
                    :value="iotStats.fault"
                    :value-style="{ color: '#fa8c16' }"
                  />
                </a-col>
              </a-row>
              <div class="mt-3">
                <a-progress
                  :percent="iotStats.onlineRate"
                  :format="(percent) => `在线率 ${percent}%`"
                  status="active"
                />
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 搜索筛选区域 -->
      <div class="search-section mb-4">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-input
              v-model:value="searchForm.roomNumber"
              placeholder="搜索房间号"
              allow-clear
            />
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="searchForm.status"
              placeholder="状态筛选"
              allow-clear
            >
              <a-select-option value="vacant">空置</a-select-option>
              <a-select-option value="reserved">已预订</a-select-option>
              <a-select-option value="rented">已出租</a-select-option>
              <a-select-option value="maintenance">维修中</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="searchForm.orientation"
              placeholder="朝向筛选"
              allow-clear
            >
              <a-select-option value="east">东</a-select-option>
              <a-select-option value="south">南</a-select-option>
              <a-select-option value="west">西</a-select-option>
              <a-select-option value="north">北</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-range-picker
              v-model:value="searchForm.rentRange"
              placeholder="租期范围"
              style="width: 100%"
            />
          </a-col>
          <a-col :span="4">
            <a-space>
              <a-button @click="resetSearch">重置</a-button>
              <a-button type="primary" @click="handleAdd"> 添加房源 </a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>

      <!-- 批量操作区域 -->
      <div
        class="batch-actions mb-4"
        v-if="searchForm.selectedRowKeys.length > 0"
      >
        <a-space>
          <span>已选择 {{ searchForm.selectedRowKeys.length }} 项</span>
          <a-button danger @click="handleBatchDelete"> 批量删除 </a-button>
        </a-space>
      </div>

      <!-- 导入导出区域 -->
      <div class="import-export mb-4">
        <a-space>
          <Upload
            :before-upload="handleImport"
            :show-upload-list="false"
            accept=".csv"
          >
            <a-button> 导入CSV </a-button>
          </Upload>
          <a-button @click="handleExport"> 导出CSV </a-button>
        </a-space>
      </div>

      <!-- 房间列表 -->
      <a-table
        :columns="columns"
        :data-source="filteredData"
        :pagination="{ pageSize: 10 }"
        :row-selection="{
          selectedRowKeys: searchForm.selectedRowKeys,
          onChange: (keys) => (searchForm.selectedRowKeys = keys),
        }"
        row-key="id"
        scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'rent'">
            ¥{{ record.rent }}
          </template>
          <template v-else-if="column.key === 'deposit'">
            ¥{{ record.deposit }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="handleIOTManagement(record)"
              >
                IoT设备
              </a-button>
              <a-button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑房源' : '添加房源'"
      @ok="handleSave"
      @cancel="handleCancel"
      width="800px"
    >
      <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="房间号" name="roomNumber">
              <a-input
                v-model:value="formData.roomNumber"
                placeholder="请输入房间号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="面积(㎡)" name="area">
              <a-input-number
                v-model:value="formData.area"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入面积"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="朝向" name="orientation">
              <a-select
                v-model:value="formData.orientation"
                placeholder="请选择朝向"
              >
                <a-select-option value="east">东</a-select-option>
                <a-select-option value="south">南</a-select-option>
                <a-select-option value="west">西</a-select-option>
                <a-select-option value="north">北</a-select-option>
                <a-select-option value="southeast">东南</a-select-option>
                <a-select-option value="southwest">西南</a-select-option>
                <a-select-option value="northeast">东北</a-select-option>
                <a-select-option value="northwest">西北</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select
                v-model:value="formData.status"
                placeholder="请选择状态"
              >
                <a-select-option value="vacant">空置</a-select-option>
                <a-select-option value="reserved">已预订</a-select-option>
                <a-select-option value="rented">已出租</a-select-option>
                <a-select-option value="maintenance">维修中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="租金(元/月)" name="rent">
              <a-input-number
                v-model:value="formData.rent"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入租金"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="押金(元)" name="deposit">
              <a-input-number
                v-model:value="formData.deposit"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入押金"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="配套设施" name="facilities">
          <a-textarea
            v-model:value="formData.facilities"
            :rows="3"
            placeholder="请输入配套设施，如：空调、热水器、WiFi等"
          />
        </a-form-item>

        <!-- 图片上传 -->
        <a-form-item label="房源图片">
          <div class="image-upload-section">
            <div class="image-list">
              <div
                v-for="(image, index) in formData.images"
                :key="index"
                class="image-item"
              >
                <img :src="image" alt="房源图片" />
                <a-button
                  type="text"
                  size="small"
                  danger
                  @click="handleRemoveImage(index)"
                  class="remove-btn"
                >
                  ×
                </a-button>
              </div>
              <Upload
                :before-upload="handleImageUpload"
                :show-upload-list="false"
                accept="image/*"
              >
                <div class="upload-btn">
                  <div>+</div>
                  <div>上传图片</div>
                </div>
              </Upload>
            </div>
          </div>
        </a-form-item>

        <a-form-item label="备注" name="remark">
          <a-textarea
            v-model:value="formData.remark"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- IoT设备管理弹窗 -->
    <a-modal
      v-model:open="iotModalVisible"
      :title="`IoT设备管理 - ${currentRoomForIOT?.roomNumber || ''}`"
      @cancel="handleIOTCancel"
      width="1200px"
      :footer="null"
    >
      <div v-if="currentRoomForIOT">
        <div class="iot-header mb-4">
          <a-descriptions :column="3" bordered>
            <a-descriptions-item label="房间号">
              {{ currentRoomForIOT.roomNumber }}
            </a-descriptions-item>
            <a-descriptions-item label="面积">
              {{ currentRoomForIOT.area }}㎡
            </a-descriptions-item>
            <a-descriptions-item label="状态">
              <a-tag :color="getStatusColor(currentRoomForIOT.status)">
                {{ getStatusText(currentRoomForIOT.status) }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- IoT设备列表 -->
        <div class="iot-devices-section">
          <div class="section-header mb-3">
            <h4>设备列表</h4>
            <a-button type="primary" size="small"> 添加设备 </a-button>
          </div>

          <a-table
            :columns="iotColumns"
            :data-source="currentRoomForIOT.iotDevices"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getDeviceStatusColor(record.status)">
                  {{ getDeviceStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'type'">
                <a-tag :color="getDeviceTypeColor(record.type)">
                  {{ getDeviceTypeText(record.type) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-button type="link" size="small">控制</a-button>
                  <a-button type="link" size="small">编辑</a-button>
                  <a-button type="link" size="small" danger>删除</a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.room-management {
  padding: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.search-section {
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.batch-actions {
  padding: 12px 16px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
}

.import-export {
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.image-upload-section {
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .image-item {
    position: relative;
    width: 100px;
    height: 80px;
    overflow: hidden;
    border: 1px solid #d9d9d9;
    border-radius: 6px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .remove-btn {
      position: absolute;
      top: 2px;
      right: 2px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 20px;
      height: 20px;
      font-size: 12px;
      color: white;
      background: rgb(0 0 0 / 60%);
      border: none;
      border-radius: 50%;
    }
  }

  .upload-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 80px;
    color: #999;
    cursor: pointer;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;

    &:hover {
      color: #1890ff;
      border-color: #1890ff;
    }
  }
}

.iot-header {
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;

  h4 {
    margin: 0;
    color: #333;
  }
}

.iot-devices-section {
  padding: 16px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}
</style>
